package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// 题目:
// 请求 http://localhost:8000/login 获取cookie
// 请求 http://localhost:8000/home	验证cookie

func AuthMiddleWare() gin.HandlerFunc {
	return func(context *gin.Context) {
		// 获取cookie并校验
		if cookie, err := context.Cookie("abc"); err == nil {
			if cookie == "123" {
				context.Next()
				return
			}
		}
		// 返回错误
		context.JSON(http.StatusUnauthorized, gin.H{"error": "err"})
		// 如果验证不通过,不调用后续函数
		context.Abort()
		return
	}
}
func main() {
	r := gin.Default()
	// 给客户端设置cookie
	r.GET("/login", func(context *gin.Context) {

		// 设置cookie
		context.SetCookie("abc", "123", 60, "/", "localhost", false, true)
		// 返回信息
		context.String(200, "login success")
	})

	r.GET("/home", AuthMiddleWare(), func(context *gin.Context) {
		context.JSON(200, gin.H{"data": "home"})
	})

	r.Run(":8000")
}
